import { get, post, put, del, type ApiResponse } from "./request";
import { RequestError } from "./request";
import type { User } from "~/types/user";
import type {
  Topic,
  TopicWithUser,
  CreateTopicRequest,
  UpdateTopicRequest,
  TopicQueryParams,
  TopicListResponse,
  ReviewTopicRequest,
  StarTopicRequest,
  TopicStats,
} from "~/types/topic";
import type {
  ResumeItem,
  CreateResumeRequest,
  UpdateResumeRequest,
} from "~/types/resume";
import type {
  Post,
  CreatePostRequest,
  PostListResponse,
  Comment,
  CreateCommentRequest,
  CommentListResponse,
  LikeRequest,
  LikeResponse,
} from "~/types/post";

/**
 * 处理API错误
 */
const handleApiError = async (error: unknown) => {
  console.error("API Error:", error);

  if (error instanceof RequestError) {
    // 处理认证错误
    if (error.status === 401) {
      // 清除用户信息
      if (import.meta.client) {
        const { useUserStore } = await import("~/stores/user");
        const userStore = useUserStore();
        userStore.setUser(null);
        userStore.setToken(null);

        // 跳转到登录页
        const { navigateTo } = await import("#app");
        navigateTo("/Login");
      }
      return;
    }

    // 显示错误消息
    if (import.meta.client) {
      console.error(`请求失败: ${error.message}`);
    }
  }

  throw error;
};

/**
 * 包装API调用，添加错误处理
 */
const wrapApiCall = async <T>(apiCall: () => Promise<T>): Promise<T> => {
  try {
    return await apiCall();
  } catch (error) {
    await handleApiError(error);
    throw error;
  }
};

// 用户相关API
export const userApi = {
  // 用户登录
  loginApi: (
    username: string,
    password: string
  ): Promise<ApiResponse<{ user: User; token: string }>> => {
    return wrapApiCall(() => post("/api/user/login", { username, password }));
  },

  // 用户注册
  registerApi: (
    userData: Partial<User> & { verificationCode: string }
  ): Promise<ApiResponse<User>> => {
    return wrapApiCall(() => post("/api/user/user", userData));
  },

  // 发送验证码
  sendVerificationCodeApi: (
    email: string
  ): Promise<ApiResponse<{ message: string; remainingTime?: number }>> => {
    return wrapApiCall(() => post("/api/user/send-code", { email }));
  },

  // 验证验证码
  verifyCodeApi: (
    email: string,
    code: string
  ): Promise<ApiResponse<{ message: string; verified?: boolean }>> => {
    return wrapApiCall(() => post("/api/user/verify-code", { email, code }));
  },

  // 获取用户信息
  getUserInfoApi: (): Promise<ApiResponse<User>> => {
    return wrapApiCall(() => get("/api/user/info"));
  },

  // 更新用户信息
  updateUserApi: (userData: Partial<User>): Promise<ApiResponse<User>> => {
    return wrapApiCall(() => put("/api/user/update", userData));
  },

  // 删除用户
  deleteUserApi: (userId: number): Promise<ApiResponse<void>> => {
    return wrapApiCall(() => del(`/api/user/${userId}`));
  },
};

// 题目相关API
export const topicApi = {
  // 获取题目列表
  getTopicsApi: (
    params?: TopicQueryParams,
    type?: string
  ): Promise<ApiResponse<TopicListResponse>> => {
    console.log(params, "-1");
    if (type === "review") {
      return wrapApiCall(() =>
        get("/api/topic", { ...params, submitterId: undefined })
      );
    }
    return wrapApiCall(() =>
      get("/api/topic", params as Record<string, unknown>)
    );
  },

  // 获取题目详情
  getTopicByIdApi: (id: number): Promise<ApiResponse<TopicWithUser>> => {
    return wrapApiCall(() => get(`/api/topic/${id}`));
  },

  // 创建题目
  createTopicApi: (
    topicData: CreateTopicRequest
  ): Promise<ApiResponse<Topic>> => {
    return wrapApiCall(() => post("/api/topic", topicData));
  },

  // 更新题目
  updateTopicApi: (
    id: number,
    topicData: UpdateTopicRequest
  ): Promise<ApiResponse<Topic>> => {
    return wrapApiCall(() => put(`/api/topic/${id}`, topicData));
  },

  // 删除题目
  deleteTopicApi: (id: number): Promise<ApiResponse<void>> => {
    return wrapApiCall(() => del(`/api/topic/${id}`));
  },

  // 审核题目
  reviewTopicApi: (
    id: number,
    reviewData: ReviewTopicRequest
  ): Promise<ApiResponse<Topic>> => {
    return wrapApiCall(() => post(`/api/topic/${id}/review`, reviewData));
  },

  // 收藏操作
  starTopicApi: (
    id: number,
    starData: StarTopicRequest
  ): Promise<ApiResponse<Topic>> => {
    return wrapApiCall(() => post(`/api/topic/${id}/star`, starData));
  },

  // 获取统计信息
  getTopicStatsApi: (
    params?: TopicQueryParams
  ): Promise<ApiResponse<TopicStats>> => {
    return wrapApiCall(() =>
      get("/api/topic/stats", params as Record<string, unknown>)
    );
  },
};

// 简历相关API
export const resumeApi = {
  // 获取简历列表
  getResumesApi: (): Promise<ApiResponse<ResumeItem[]>> => {
    return wrapApiCall(() => get("/api/resume"));
  },

  // 获取简历详情
  getResumeByIdApi: (id: number): Promise<ApiResponse<ResumeItem>> => {
    return wrapApiCall(() => get(`/api/resume/${id}`));
  },

  // 创建简历
  createResumeApi: (
    data: CreateResumeRequest
  ): Promise<ApiResponse<ResumeItem>> => {
    return wrapApiCall(() => post("/api/resume", data));
  },

  // 更新简历
  updateResumeApi: (
    id: number,
    data: UpdateResumeRequest
  ): Promise<ApiResponse<ResumeItem>> => {
    return wrapApiCall(() => put(`/api/resume/${id}`, data));
  },

  // 删除简历
  deleteResumeApi: (id: number): Promise<ApiResponse<void>> => {
    return wrapApiCall(() => del(`/api/resume/${id}`));
  },
};

// 帖子相关API
export const postApi = {
  // 获取帖子列表
  getPostsApi: (params?: {
    page?: number;
    pageSize?: number;
    search?: string;
    sort?: string;
  }): Promise<ApiResponse<PostListResponse>> => {
    return wrapApiCall(() => get("/api/post", params));
  },

  // 获取帖子详情
  getPostByIdApi: (id: number): Promise<ApiResponse<Post>> => {
    return wrapApiCall(() => get(`/api/post/${id}`));
  },

  // 创建帖子
  createPostApi: (data: CreatePostRequest): Promise<ApiResponse<Post>> => {
    return wrapApiCall(() => post("/api/post", data));
  },

  // 更新帖子
  updatePostApi: (
    id: number,
    data: CreatePostRequest
  ): Promise<ApiResponse<void>> => {
    return wrapApiCall(() => put(`/api/post/${id}`, data));
  },

  // 删除帖子
  deletePostApi: (id: number): Promise<ApiResponse<void>> => {
    return wrapApiCall(() => del(`/api/post/${id}`));
  },
};

// 评论相关API
export const commentApi = {
  // 获取评论列表
  getCommentsApi: (params?: {
    postId: number;
    page?: number;
    pageSize?: number;
  }): Promise<ApiResponse<CommentListResponse>> => {
    return wrapApiCall(() => get("/api/comment", params));
  },

  // 获取评论详情
  getCommentByIdApi: (id: number): Promise<ApiResponse<Comment>> => {
    return wrapApiCall(() => get(`/api/comment/${id}`));
  },

  // 创建评论
  createCommentApi: (
    data: CreateCommentRequest
  ): Promise<ApiResponse<Comment>> => {
    return wrapApiCall(() => post("/api/comment", data));
  },

  // 更新评论
  updateCommentApi: (
    id: number,
    data: { content: string }
  ): Promise<ApiResponse<Comment>> => {
    return wrapApiCall(() => put(`/api/comment/${id}`, data));
  },

  // 删除评论
  deleteCommentApi: (id: number): Promise<ApiResponse<void>> => {
    return wrapApiCall(() => del(`/api/comment/${id}`));
  },

  // 获取评论的回复列表
  getRepliesApi: (params: {
    commentId: number;
    page?: number;
    pageSize?: number;
  }): Promise<ApiResponse<CommentListResponse>> => {
    return wrapApiCall(() =>
      get(`/api/comment/${params.commentId}/replies`, {
        page: params.page,
        pageSize: params.pageSize,
      })
    );
  },
};

// 点赞相关API
export const likeApi = {
  // 切换点赞状态
  toggleLikeApi: (data: LikeRequest): Promise<ApiResponse<LikeResponse>> => {
    return wrapApiCall(() => post("/api/like/toggle", data));
  },

  // 检查点赞状态
  checkLikeApi: (params: {
    targetType: "post" | "comment";
    targetId: number;
  }): Promise<ApiResponse<{ isLiked: boolean }>> => {
    return wrapApiCall(() => get("/api/like/check", params));
  },
};

// 导出所有API
export default {
  user: userApi,
  topic: topicApi,
  resume: resumeApi,
  post: postApi,
  comment: commentApi,
  like: likeApi,
};
